<template>
  <div ref="Pie" :class="className" :style="{ height: height, width: width }" />
</template>

<script setup name="Pie">
import * as echarts from 'echarts'
import { toRefs } from 'vue'

const Pie = ref(null)
const animationDuration = ref(3000)

const props = defineProps({
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '100%'
  },
  height: {
    type: String,
    default: '500px'
  },
  elementData: {
    type: Object,
    default: undefined
  }
});

const { className, width, height, elementData } = toRefs(props)

watch(elementData, (newValue, oldValue) => {
  initChart()
})

/** 初始化图标 */
function initChart() {
  if (Pie.value) {
    var myChart = echarts.init(Pie.value);

    let option = {
      title: {},
      tooltip: {
        trigger: 'item'
      },
      legend: {},
      series: [
        {
          type: 'pie',
          radius: '50%',
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    }

    if(elementData.value){
      if(elementData.value.element.titleText){
        option.title.text = elementData.value.element.titleText
      }
      if(elementData.value.element.titleSubtext){
        option.title.subtext = elementData.value.element.titleSubtext
      }
      if(elementData.value.element.titleLeft){
        option.title.left = elementData.value.element.titleLeft
      }
      if(elementData.value.element.tooltip){
        option.tooltip.show = elementData.value.element.tooltip
      }
      if(elementData.value.element.legend){
        option.legend.show = elementData.value.element.legend
      }
      if(elementData.value.element.legendLeft){
        option.legend.left = elementData.value.element.legendLeft
      }
      if(elementData.value.seriesName){
        option.series[0].name = elementData.value.seriesName
      }
      if(elementData.value.series){
        option.series[0].data = elementData.value.series
      }
    }

    setTimeout(() => {
      myChart.setOption(option)
      myChart.resize()
    }, 0);
  }
}

initChart();
</script>
